package com.wiegand.util {
	import flash.display.Sprite;
	import flash.utils.Dictionary;

	/**
	 * @author gandy
	 */
	public class MaterialsList {

		protected var _materialsDic :Dictionary;
		protected var _materials :Array;
		private var _materialsTotal :int;
		public var _materialsByNameDic :Dictionary;
	
		public function get numMaterials():int{
			return _materialsTotal;
		}

		public function MaterialsList( materials : Array = null ):void{
			_materials = materials;
			if(materials == null)_materials = new Array();
			_materialsByNameDic  = new Dictionary(true);
			_materialsDic       = new Dictionary(false);
			_materialsTotal  = 0;
	
			if( materials ){
				if( materials is Array ){
					for( var i:String in materials ){
						addMaterial( materials[i] );
					}
				}
			}
		}

		public function addMaterial( material:Sprite, name:String=null ):void{
			name = name || material.name;
			_materials.push(material);
			_materialsDic[ material ] = name;
			_materialsByNameDic[ name ] = material;
			_materialsTotal++;
		}
	
		public function removeMaterial( material:Sprite ):Sprite{
			if(this._materialsDic[ material ]){
				delete this._materialsByNameDic[ this._materialsDic[ material ] ];
				delete this._materialsDic[ material ];
				_materialsTotal--;
			}
			return material;
		}

		public function getMaterialByName( name:String ):Sprite{
			return this._materialsByNameDic[name] ? this._materialsByNameDic[name] : this._materialsByNameDic["all"];
		}

		public function removeMaterialByName( name:String ):Sprite{
			return removeMaterial( getMaterialByName( name ) );
		}
	
		public function toString():String{
			var list:String = "";
			for each( var m:Sprite in this._materialsByNameDic )
				list += this._materials[ m ] + "\n";
			return list;
		}
		
		public function getMaterialsAsArray():Array{
			return _materials;
		}
	}
}